package xkp.lesson.springboot_shiro.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xkp.lesson.springboot_shiro.entity.Building;
import xkp.lesson.springboot_shiro.entity.JsonData;
import xkp.lesson.springboot_shiro.entity.UserInfo;
import xkp.lesson.springboot_shiro.service.BuildingService;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/building")
public class BuildingController {
    @Resource
    private BuildingService buildingService;

    @RequiresPermissions("building:list")
    @GetMapping("/listbyUserId")
    public JsonData<List<Building>> selectByUserId(){
        Subject currentUser = SecurityUtils.getSubject();
        UserInfo userInfo = (UserInfo) currentUser.getPrincipal();
        Integer userId = userInfo.getUserId();
        JsonData<List<Building>> jsonData = new JsonData<>();
        jsonData.setData(buildingService.selectAllByUserId(userId));
        jsonData.setCode(1);
        jsonData.setMsg("查询成功");
        return jsonData;
    }

    @RequiresPermissions("building:saveBuild")
    @PostMapping("/saveBuild")
    public JsonData saveBuild(Building building){
        JsonData jsonData = new JsonData();
        Subject currentUser = SecurityUtils.getSubject();
        UserInfo userInfo = (UserInfo) currentUser.getPrincipal();
        Integer userId = userInfo.getUserId();
        building.setUserId(userId);
        MultipartFile buildImg = building.getBuildImg();
        building.setImg(buildImg.getOriginalFilename());


        if(!buildImg.isEmpty()){
            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/upload/images";
            building.setImgUrl("/upload/images/"+building.getImg());
            File file = new File(path,building.getImg());
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            try {
                buildImg.transferTo(file);
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        buildingService.insert(building);
        jsonData.setCode(1);
        jsonData.setMsg("保存成功");
        return jsonData;
    }
}
